package com.gitee.chili.leisure.util;

import com.gitee.chili.leisure.ResponseCode;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;

/**
 * EnumUtil
 *
 * @author week solider
 * @since 2020-07-30
 */
public class Enum {

    /** 枚举实例缓存 */
    private static final Map<Class<?>, Object> ENUMS = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    public static <E extends java.lang.Enum<E>> E valueOf(Class<E> clazz, Predicate<E> predicate) {

        Object obj = ENUMS.get(clazz);
        E[] e;
        if (obj == null) {
            e = clazz.getEnumConstants();
            ENUMS.put(clazz, e);
        } else {
            e = (E[]) obj;
        }
        return Arrays.stream(e).filter(predicate).findAny().orElse(null);
    }

    public static void main(String[] args) {
        System.out.println(valueOf(ResponseCode.class, e -> e.getCode().equals(200)));
    }
}
